/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package semant.first_pass;

import semant.Env;
import symbol.ClassInfo;
import symbol.MethodInfo;
import symbol.Symbol;
import symbol.VarInfo;
import syntaxtree.VarDecl;
import syntaxtree.VisitorAdapter;

/**
 *
 * @author Thiago
 */
class AttributeHandler extends VisitorAdapter {


    private Env env;
    private ClassInfo info;
    private MethodInfo method;

    private AttributeHandler(Env e, ClassInfo i)
    {
        env = e;

        info = i;
    }

    private AttributeHandler(Env e,ClassInfo c, MethodInfo m)
    {
        env = e;

        method = m;

        info = c;
    }

    static void firstPass(Env e, ClassInfo i, VarDecl node) {

        AttributeHandler h = new AttributeHandler(e,i);

        node.accept(h);
    }

    static void firstPass(Env e, ClassInfo c, MethodInfo m, VarDecl node) {
        
        AttributeHandler h = new AttributeHandler(e,c,m);

        node.accept(h);
    }

    @Override
    public void visit(VarDecl node)
    {
        Symbol name = Symbol.symbol(node.name.s);

        VarInfo v = new VarInfo(node.type, name);


        if(method == null)
        {
            if(!info.addAttribute(v))
            {
                VarInfo old = info.attributes.get(name);

                env.err.Error(node.name, new Object[]{"Atributo \'"+ name + "\' redeclarado para a classe \'" + info.name + "\'",
                                            "Declaração anterior aqui: [" + old.type.line + "," + old.type.row + "]"});
            }
        }
        else
        {
            if(!method.addLocal(v))
            {
                VarInfo old = method.localsTable.get(name);

                if(old == null)
                    old = method.formalsTable.get(name);

                env.err.Error(node.name, new Object[]{"Atributo \'"+ name + "\' redeclarado para o método \'" + method.name + "\' na classe \'" + info.name.toString() +"\'",
                                            "Declaração anterior aqui: [" + old.type.line + "," + old.type.row + "]"});
            }
        }

    }

}
